import type { TTSTaskInfo } from '@/api/ai/tts'

const DB_NAME = 'huahua-api-tts';
const DB_VERSION = 1;
const STORE_NAME = 'tts-history';

/**
 * IndexedDB 数据库管理类
 */
class TTSStorage {
  private db: IDBDatabase | null = null;

  /**
   * 初始化数据库
   */
  private async initDB(): Promise<IDBDatabase> {
    if (this.db) {
      return this.db;
    }

    return new Promise((resolve, reject) => {
      const request = indexedDB.open(DB_NAME, DB_VERSION);

      request.onerror = () => {
        reject(new Error('Failed to open IndexedDB'));
      };

      request.onsuccess = () => {
        this.db = request.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result;
        
        // 创建对象存储
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' });
          
          // 创建索引
          store.createIndex('createdTime', 'createdTime', { unique: false });
          store.createIndex('status', 'status', { unique: false });
        }
      };
    });
  }

  /**
   * 保存TTS任务记录
   */
  async saveTTSTask(taskInfo: TTSTaskInfo): Promise<void> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      
      const request = store.put({
        ...taskInfo,
        savedAt: new Date().toISOString() // 添加保存时间
      });

      request.onsuccess = () => resolve();
      request.onerror = () => reject(new Error('Failed to save TTS task'));
    });
  }

  /**
   * 获取所有TTS历史记录
   */
  async getTTSHistory(): Promise<TTSTaskInfo[]> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readonly');
      const store = transaction.objectStore(STORE_NAME);
      
      // 获取所有记录
      const request = store.getAll();

      request.onsuccess = () => {
        const results = request.result as TTSTaskInfo[];
        // 按ID降序排列（ID越大越新）
        results.sort((a, b) => {
          if (a.id !== b.id) {
            return b.id - a.id;
          }
          // 如果ID相同，按创建时间降序
          const dateA = new Date(a.createdTime).getTime();
          const dateB = new Date(b.createdTime).getTime();
          return dateB - dateA;
        });
        resolve(results);
      };

      request.onerror = () => reject(new Error('Failed to get TTS history'));
    });
  }

  /**
   * 根据ID获取TTS任务记录
   */
  async getTTSTaskById(id: number): Promise<TTSTaskInfo | null> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readonly');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.get(id);

      request.onsuccess = () => {
        resolve(request.result || null);
      };

      request.onerror = () => reject(new Error('Failed to get TTS task'));
    });
  }

  /**
   * 删除TTS任务记录
   */
  async deleteTTSTask(id: number): Promise<void> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.delete(id);

      request.onsuccess = () => resolve();
      request.onerror = () => reject(new Error('Failed to delete TTS task'));
    });
  }

  /**
   * 清空所有TTS历史记录
   */
  async clearTTSHistory(): Promise<void> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.clear();

      request.onsuccess = () => resolve();
      request.onerror = () => reject(new Error('Failed to clear TTS history'));
    });
  }

  /**
   * 获取历史记录数量
   */
  async getHistoryCount(): Promise<number> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readonly');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.count();

      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(new Error('Failed to count TTS history'));
    });
  }

  /**
   * 获取未完成的任务列表
   */
  async getIncompleteTasks(): Promise<TTSTaskInfo[]> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readonly');
      const store = transaction.objectStore(STORE_NAME);
      const statusIndex = store.index('status');
      
      const results: TTSTaskInfo[] = [];
      
      // 获取 PENDING 状态的任务
      const pendingRequest = statusIndex.openCursor(IDBKeyRange.only('PENDING'));
      let pendingCount = 0;
      
      pendingRequest.onsuccess = (event) => {
        const cursor = (event.target as IDBRequest).result;
        if (cursor) {
          results.push(cursor.value);
          cursor.continue();
        } else {
          // PENDING 处理完成，开始处理 PROCESSING
          const processingRequest = statusIndex.openCursor(IDBKeyRange.only('PROCESSING'));
          
          processingRequest.onsuccess = (processingEvent) => {
            const processingCursor = (processingEvent.target as IDBRequest).result;
            if (processingCursor) {
              results.push(processingCursor.value);
              processingCursor.continue();
            } else {
              // 全部处理完成
              resolve(results);
            }
          };
          
          processingRequest.onerror = () => reject(new Error('Failed to get PROCESSING tasks'));
        }
      };

      pendingRequest.onerror = () => reject(new Error('Failed to get PENDING tasks'));
    });
  }

  /**
   * 批量更新任务状态
   */
  async updateTasksStatus(tasks: TTSTaskInfo[]): Promise<void> {
    const db = await this.initDB();
    
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      
      let completed = 0;
      const total = tasks.length;
      
      if (total === 0) {
        resolve();
        return;
      }
      
      tasks.forEach(task => {
        const request = store.put({
          ...task,
          savedAt: new Date().toISOString()
        });
        
        request.onsuccess = () => {
          completed++;
          if (completed === total) {
            resolve();
          }
        };
        
        request.onerror = () => {
          reject(new Error(`Failed to update task ${task.id}`));
        };
      });
    });
  }

  /**
   * 关闭数据库连接
   */
  close(): void {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }
}

// 导出单例实例
export const ttsStorage = new TTSStorage();